const mongoose = require('mongoose');
const Cate = require('../models/cate.model');

//自己建了一个函数,将users.js中的函数写道exports
exports.creat = function(req, res, next) {
    var cate = new Cate(req.body);
    cate.save().then(data => {
        //console.log(data);
        res.json(data); //以json形式进行数据返回
    })
};

//修改数据
exports.update = function(req, res, next) {
    const id = req.params.id;
    Cate.findByIdAndUpdate(id, { $set: req.body }).then(data => {
        res.json(data);
    })

};

//删除
exports.remove = function(req, res, next) {
    var id = req.params.id;
    var ids = [];
    Cate.findOne({ _id: id }, function(err, doc) {
        //console.log(doc);
        ids = [doc.id];
        doc.getChildren().then(function(docs) {
            //console.log(docs);
            for (var i = 0; i < docs.length; i++) {
                ids.push(docs[i]._id);
                //console.log(ids);
            }
            Cate.remove({ _id: { $in: ids } }).then(data => {
                res.json({ message: 'delete ok' });
            });
        });
    });
};


//查询

function reverseTree(data, pid) { //data就是一个平行的数组，要做的是把它变成一个嵌套的结构
    var result = [],
        temp;
    var data = JSON.parse(JSON.stringify(data)); //为什么?数据模型里面没有一个children节点，需要添加children，将data转换成字符串(将数据模型转换成字符串),将字符串转换成json object，现在的object不是数据模型的对象，变成了普通的json object

    for (var i in data) {
        if (data[i].parentId === pid) {
            result.push(data[i]);

            temp = reverseTree(data, data[i]._id); //将新闻的_id当成parentId
            if (temp.length > 0) {
                data[i].children = temp; //他的儿子就是取出的对象
            }
        }
    }
    return result; //要返回
};

exports.list = function(req, res, next) {
    var type = req.params.type || 1; //如果有选中，没有默认选1

    Cate.find({ type: type }, (err, data) => {
        //console.log(data);
        var rpTree = reverseTree(data, null);
        res.json(rpTree);
    })

};

//获取数据
exports.get = function(req, res, next) {
    const id = req.params.id;
    Cate.findById(id).then(data => {
        res.json(data);
    })
}